/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28318
 * Date: 2025-11-05
 * Time: 21:47
 */
public class MyArraylist {

    public int[] elem;
    public int usedSize;//0
    //默认容量
    private static final int DEFAULT_SIZE = 10;

    public MyArraylist() {
        this.elem = new int[DEFAULT_SIZE];
    }

    /**
     * 打印顺序表:
     * 根据usedSize判断即可
     */
    public void display() {
        System.out.print("[ ");
        for (int i = 0; i < this.usedSize; i++) {
            System.out.println(this.elem[i] + " ");
        }
        System.out.println("]");
    }

    // 新增元素,默认在数组最后新增
    public void add(int data) {
        if (this.isFull()) {
            this.elem = grow();
        }
        this.elem[this.usedSize] = data;
    }

    /**
     * 判断当前的顺序表是不是满的！
     *
     * @return true:满   false代表空
     */
    public boolean isFull() {
        if (this.elem.length != this.usedSize){
            return false;
        }
        return true;
    }


    private boolean checkPosInAdd(int pos) {
        if (this.isFull()){
            return false;
        }
        if (pos >= this.usedSize){
            return false;
        }
        return true;//合法
    }

    // 在 pos 位置新增元素
    public void add(int pos, int data) {
        if (!this.checkPosInAdd(pos)){
            for (int i = this.usedSize - 1; i > pos ; i--) {
                this.elem[i] = this.elem[i - 1];
            }
            this.elem[pos] = data;
        }
    }

    // 为 elem 扩容，默认容量扩容
    private int[] grow(){
        int[] ret = new int[this.elem.length + DEFAULT_SIZE];
        for (int i = 0; i < this.elem.length; i++) {
            ret[i] = this.elem[i];
        }
        return ret;
    }

    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        if (this.indexOf(toFind) >= 0){
            return true;
        }
        return false;
    }

    // 查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }

    // 获取 pos 位置的元素
    public int get(int pos) {
        if (this.checkPosInAdd(pos)){
            return this.elem[pos];
        }
        return -1;
    }

    private boolean isEmpty() {
        if (this.isFull()){
            return false;
        }
        return true;
    }

    // 给 pos 位置的元素设为【更新为】 value
    public void set(int pos, int value) {
        if (this.checkPosInAdd(pos)){
            this.elem[pos] = value;
        }
    }

    /**
     * 删除第一次出现的关键字key
     *
     * @param key
     */
    public void remove(int key) {
        int pos = this.indexOf(key);
        if (pos == -1){
            return;
        }
        for (int i = pos; i < this.usedSize - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
    }

    // 获取顺序表长度
    public int size() {
        return this.usedSize;
    }

    // 清空顺序表
    public void clear() {
        this.usedSize = 0;
    }
}